package com.hengtongxing.hejiayun.shop;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.bean.CommentBean;
import com.hengtongxing.hejiayun.bean.ImageBean;
import com.hengtongxing.hejiayun.bean.OrderListBean;
import com.hengtongxing.hejiayun.event.OrderRefushEvent;
import com.hengtongxing.hejiayun.homepage.model.HomePageModelImpl;
import com.hengtongxing.hejiayun.homepage.model.IHomePageModel;
import com.hengtongxing.hejiayun.shop.adapter.Adapter_PictureSelector;
import com.hengtongxing.hejiayun.shop.adapter.OrderEvaluateListAdapter;
import com.hengtongxing.hejiayun.shop.model.IShopModel;
import com.hengtongxing.hejiayun.shop.model.ShopModelImpl;
import com.hengtongxing.hejiayun.utils.Base64BitmapUtil;
import com.hengtongxing.hejiayun.utils.GlideEngine;
import com.hengtongxing.hejiayun.utils.PermissionsManager;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.ViewLoading;
import com.hengtongxing.hejiayun.widget.WrapContentLinearLayoutManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class EvaluateOrderActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private String order_id;
    private List<OrderListBean.DataBean.ItemListBean.ShopOrderGoodsBean> goodsBeanList;
    private OrderEvaluateListAdapter listAdapter;
    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private Adapter_PictureSelector adapter;
    private IHomePageModel homePageModel;
    private IShopModel shopModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate_order);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        shopModel = new ShopModelImpl();
        homePageModel = new HomePageModelImpl();
        permissionsManager = new PermissionsManager(this);
        order_id = getIntent().getStringExtra("order_id");
        goodsBeanList = (List<OrderListBean.DataBean.ItemListBean.ShopOrderGoodsBean>) getIntent().getSerializableExtra("goodsBeanList");
        listAdapter = new OrderEvaluateListAdapter(goodsBeanList);

        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener(new OrderEvaluateListAdapter.onCallBackListener() {
            @Override
            public void showPictureSelect(Adapter_PictureSelector adapter1, int position) {
                adapter = adapter1;
                showPictureSelectorDialog();

            }

            @Override
            public void handlerAdapterItem(Adapter_PictureSelector adapter1, int position, int childPosition) {
                adapter = adapter1;
                handlerAdapterItemClick(childPosition);
            }
        });
        titleBar.setRightClickListener(() -> {
            List<CommentBean> comment_list = new ArrayList<>();
            for (OrderListBean.DataBean.ItemListBean.ShopOrderGoodsBean orderGoodsBean : goodsBeanList) {
                if (TextUtils.isEmpty(orderGoodsBean.getComment())) {
                    ToastUtil.showShort("请发表你的想法");
                    return;
                }
                CommentBean commentBean = new CommentBean();
                commentBean.setGoods_id(orderGoodsBean.getShop_goods_id() + "");
                commentBean.setComment(orderGoodsBean.getComment());
                commentBean.setImg(orderGoodsBean.getImgList());
                comment_list.add(commentBean);
            }
            commit(comment_list);
        });
    }

    public void commit(List<CommentBean> comment_list) {
        shopModel.requestGoodsComment(order_id, comment_list, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("发布成功");
                EventBus.getDefault().post(new OrderRefushEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(this, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    private void handlerAdapterItemClick(int position) {

//        List<LocalMedia> selectList = adapter.getMediaList();
//
//        if (selectList != null && selectList.size() > 0) {
//            PictureSelector.create(this).externalPicturePreview(position, selectList, 0);
//        }
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }


    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }


    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(mActivity)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                List<LocalMedia> list = new ArrayList<>();
                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(bean.getData().getUrl());
                list.add(localMedia);
                adapter.addMediaList(list);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

}
